package com.enzoism.springboot.dive.mock;

import com.enzoism.springboot.dive.lock.DistributedLocker;
import com.enzoism.springboot.dive.lock.RedissonConnector;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 模拟数据库进行数据交易(单例类)
 */
@Component()
public class MockDataSource {

    private final static String LOCKER_PREFIX = "lock:";

    @Autowired
    private RedissonConnector redissonConnector;

    private Integer coutNum;

    public Integer getCoutNum() {
        return coutNum;
    }

    public void setCoutNum(Integer coutNum) {
        String key = "dec_store_lock_countNum";
        RedissonClient redisson= redissonConnector.getClient();
        RLock lock = redisson.getLock(LOCKER_PREFIX + key);
        long lockTime = 100;
        try {
            boolean success = lock.tryLock(100, lockTime, TimeUnit.SECONDS);
            if (success) {
                try {
                    System.out.println("------【" + Thread.currentThread().getName() + " 】锁获取成功");
                    this.coutNum = coutNum;
                    Thread.sleep(new Random().nextInt(1000));
                } finally {
                    //解锁
                    System.out.println("------锁释放成功");
                    lock.unlock();
                }
            }else{
                System.out.println("------------当前锁正在使用");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
